from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import  By
from selenium.common.exceptions import NoSuchElementException
wd = webdriver.Chrome(service=Service(r'/Users/tonywu/downloads/Mess/chromedriver/chromedriver'))
wd.get("http://www.baidu.com")
try:
    # 而且关系
    element = wd.find_element(By.CSS_SELECTOR,'span.title-content-title')
    print(element.get_attribute('outerHTML'))
    element = wd.find_element(By.CSS_SELECTOR, '[href="https://pss.bdstatic.com/static/superman/css/ubase_sync-d600f57804.css?v=md5"]')
    print(element.get_attribute('outerHTML'))
    # 或关系用,号;优先级最低
    '''
    不支持括号。只能这样 #t1 > span, #t1 > p; 不能 #t1 >(span,p);
    '''
    element2 = wd.find_elements(By.CSS_SELECTOR,'span.title-content-title,[href="https://pss.bdstatic.com/static/superman/css/ubase_sync-d600f57804.css?v=md5"]')
    for el in element2:
        print(el.get_attribute('outerHTML'))

    # 按次序选子节点 - 包括父
    element = wd.find_element(By.CSS_SELECTOR, '#hotsearch-content-wrapper:nth-child(2)')
    print(element.get_attribute('outerHTML')) # outerHTML包括匹配上的元素+父元素
    element = wd.find_element(By.CSS_SELECTOR, '#hotsearch-content-wrapper:nth-last-child(1)')
    print(element.get_attribute('innerHTML'))
    element = wd.find_element(By.CSS_SELECTOR, '#hotsearch-content-wrapper:nth-last-child(odd)')
    print(element.get_attribute('innerHTML'))
    # 纯同一类集合
    element = wd.find_element(By.CSS_SELECTOR, '.hotsearch-item:nth-of-type(2)')
    print(element.get_attribute('innerHTML'))
    element = wd.find_element(By.CSS_SELECTOR, '.hotsearch-item:nth-last-of-type(2)')
    print(element.get_attribute('innerHTML'))
    '''
    # 一个兄弟
    h3 + span
    # 所有的兄弟span
    h3 ~ span
    '''

except NoSuchElementException as e:
    print(e.msg)
input()